﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Hxsoft.AppV1.Module;

namespace Hxsoft.AppV1.Admin.CacheManage
{
	public partial class RegisterSqlCacheDependency : BasePage
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (RightValidate())
			{
				if (!IsPostBack)
				{
					LoadList();
					this.DataBind();
				}
			}
		}

		protected void BtnEnableSqlCacheDependency_Click(object sender, EventArgs e)
		{
			SqlCacheDependency.EnableNotifications();
			LoadList();
		}

		protected void BtnDisableSqlCacheDependency_Click(object sender, EventArgs e)
		{
			SqlCacheDependency.DisableNotifications();
			LoadList();
		}

		protected void BtnEnableTableForNotifications_Click(object sender, EventArgs e)
		{
			SqlCacheDependency.EnableTableForNotifications(TbTableName.Text);
			LoadList();
		}

		protected void ListTablesEnabledForNotifications_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			string tableName = GetItemTableName(e.Item);

			switch (e.CommandName)
			{
				case "DisableTableForNotifications":
					SqlCacheDependency.DisableTableForNotifications(tableName);
					break;
			}

			LoadList();
		}

		#region Method
		/// <summary>
		/// 加载启用通知的数据表。
		/// </summary>
		protected void LoadList()
		{
			try
			{
				ListTablesEnabledForNotifications.DataSource = SqlCacheDependency.GetTablesEnabledForNotifications();
				ListTablesEnabledForNotifications.DataBind();
			}
			catch
			{
				ListTablesEnabledForNotifications.DataSource = null;
				ListTablesEnabledForNotifications.DataBind();
			}
		}

		/// <summary>
		/// 取得指定项的表名。
		/// </summary>
		/// <param name="item">项</param>
		/// <returns>指定项的表名。</returns>
		protected string GetItemTableName(RepeaterItem item)
		{
			string tableName;
			Label control;

			control = (Label)item.FindControl("LbTableName");
			tableName = control.Text;

			return tableName;
		}

		/// <summary>
		/// 返回权限验证结果，如果验证失败则显示消息提示。
		/// </summary>
		/// <returns>布尔值代表权限验证是否通过。</returns>
		public bool RightValidate()
		{
			bool right = SqlCacheDependency.GetManageRight();
			if (!right)
			{
				Messages.Add(new PageMessage(false, null, PageMessageType.Error, Res.PermissionExceptionMessageTitle, Res.PermissionExceptionMessage));
			}
			return right;
		}
		#endregion
	}
}
